﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Obligatorio.DataAccess;

/// <summary>
/// Summary description for CashRegisterPresenter
/// </summary>
public class CashRegisterPresenter
{
    #region Fields
    ICashRegisterView _view;
    #endregion

    public CashRegisterPresenter(ICashRegisterView view)
    {
        this._view = view;
    }

    public void GetUserBranch()
    {
        using (var data = new ObligatorioDotNetEntities())
        {
            this._view.BranchId = data.Users.Where(u => u.UserId == this._view.UserId).Single().BranchId;
        }
    }

    public void GetProducts()
    {
        using (var data = new ObligatorioDotNetEntities())
        {
            this._view.Products = data.ProductStocks.Where(ps => ps.BranchId == this._view.BranchId &&
                ps.Quantity > 0).Select(ps => ps.Product).ToList();
        }
    }

    public bool InsertProductPurchase()
    {
        using (var data = new ObligatorioDotNetEntities())
        {
            PurchaseProduct pp = new PurchaseProduct()
            {
                ProductId = this._view.ProductId,
                Quantity = this._view.Quantity,
                PurchaseId = this._view.PurchaseId
            };

            var stock = data.ProductStocks.Where(ps => ps.ProductId == this._view.ProductId &&
                ps.BranchId == this._view.BranchId).Single();

            if (stock.Quantity >= this._view.Quantity)
            {
                stock.Quantity -= this._view.Quantity;


                if (stock.Quantity  > stock.AlertThreshold)
                {
                    ///TODO: Send Alert
                }
                data.PurchaseProducts.AddObject(pp);

                data.SaveChanges();

                return true;
            }

            return false;

            
        }
    }

    public void CreatePurchase()
    {
        using (var data = new ObligatorioDotNetEntities())
        {
            Purchase p = new Purchase { BranchId = this._view.BranchId, Date = DateTime.Now, StatusId = 1};
            data.Purchases.AddObject(p);
            data.SaveChanges();
            this._view.PurchaseId = p.PurchaseId;
        }
    }

    public string GetProduct(long productId)
    {
        using (var data = new ObligatorioDotNetEntities())
        {
            return data.Products.Where(p => p.ProductId == productId).Single().ProductDesctiption;
        }
    }
}